package cn.itacst.myServlet;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;

public class ApplicationJsonServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("ApplicationJsonServlet类的doGet方法执行了");


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ApplicationJsonServlet类的doPost方法执行了");

        System.out.println(System.getProperty("file.encoding"));


        // 设置请求编码（其实 JSON 不受这影响，但统一写）
//        request.setCharacterEncoding("UTF-8");
//        request.setCharacterEncoding("GBK");


        String contentType = request.getContentType();
        System.out.println("content-type:" + contentType);

        String charset="utf-8";

//        if (contentType.toLowerCase().contains("charset=")) {
//            charset = contentType.toLowerCase().split("charset=")[1];
//        }

        System.out.println("设置的charset:" + charset);
        charset="utf-8";
        charset="gbk";
        System.out.println("再次手动设置的charset:" + charset);

        ServletInputStream inputStream = request.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream, charset.toUpperCase());
        BufferedReader br = new BufferedReader(reader);

        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            jsonBuilder.append(line);
        }

        String json = jsonBuilder.toString();

        System.out.println("收到 JSON：" + json);

        System.out.println(URLDecoder.decode(json, "gbk"));


        response.setContentType("text/plain;charset=GBK");
//        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().write("服务端已接收：" + URLDecoder.decode(json, "gbk"));

    }
}
